<template>

  <el-card style="min-height: 350px">
    <div slot="header" style="display: flex;justify-content: space-between;align-items: center">
      <span>产品产线配置</span>

      <el-button
        @click="submitFormData('formData')"
        icon="el-icon-coin"
        type="primary"
      >保存产品产线配置
      </el-button>
    </div>

    <el-alert
      effect="dark"
      show-icon
      style="margin-bottom: 10px;"
      title="`配置产品和组件的生产线路"
      type="success"
    >
    </el-alert>

    <!--  <azure-line-select-->
    <!--    :product-id="$route.query.ProductId"-->
    <!--    :selectItemList.sync="formData.productLineItemList"-->
    <!--    :value.sync="formData.productLineIdList"/>-->

    <!--   model 非常重要 -->
    <el-form :label-width="globalLabelWidth" :model="formData" :rules="rules" ref="formData">
      <el-row :gutter="globalGutter">
        <el-col v-bind="globalGrid">
          <el-form-item label="产品线" prop="selectIds">
            <el-select
              :key="key"
              @change="handleProductLineChange"
              multiple
              placeholder="请选择产品线" style="width:100%" v-model="formData.selectIds">
              <el-option
                :key="item.lineId"
                :label="item.name"
                :value="item.lineId"
                v-for="item in enumList"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-bind="globalGrid">
          <el-form-item label="默认产品线" prop="defaultProductLine">
            <a-select
              :options="selectProductItem"
              :value.sync="formData.defaultProductLine"
              @change="handleProductDefaultLineChange"
              label-attr-name="name"
              placeholder="请选择默认产线"
              val-attr-name="lineId"/>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
  </el-card>
</template>

<script>
  import ASelect from '@/components/ATheFridayClub/ASelect'
  import {
    DeleteProductLine,
    getAllLine,
    ModifyProductLine,
    ProductPrintTypeGetAll,
    QueryProductLine
  } from '@/api/productInformation'
  import { ERR_OK } from '@/utils/commons'
  import { debugLogger } from '@/utils/fridayClub/functianal'
  import layoutMixin from '@/mixins/layoutMixin'
  import form from '@/mixins/form'
  import AButton from '@/components/ATheFridayClub/AButton'
  import { deepClone } from '@/utils'

  export default {
    name: 'azureLineSelect',
    components: { AButton, ASelect },
    props: {
      resultItems: {
        type: Array,
        default: () => ([])
      },
      productId: {  //  组件ID
        type: [Number, String],
        require: true
      }
    },
    mixins: [layoutMixin, form],

    data() {
      this.rules = {
        selectIds: [
          { type: 'array', required: true, message: '必须配置一条产品线', trigger: ['change', 'blur'] }
        ],
        defaultProductLine: [
          { required: true, message: '必须选择一条默认产品线为默认', trigger: ['change', 'blur'] }
        ]
      }
      return {
        // data: Array.of(),
        key: new Date().getTime(),
        // selectItemList: [],  //  选择的产品线items
        formData: {
          selectIds: [], //  select ids
          defaultProductLine: '' //  默认的产品线
        },
        enumList: Array.of(), //  all

        originLineList: []
      }
    },
    computed: {
      selectProductItem() {
        return this.enumList.filter(e => this.formData.selectIds.includes(e.lineId))
      }
    },

    async created() {
      const lineList = await this.getRelate()
      const Items = await this.getAll()

      this.calculate({ lineList, Items })

      this.originLineList = deepClone(lineList)
      this.handleProductDefaultLineChange()
      this.handleProductLineChange()
      // this.clearValidate()
    },

    methods: {
      async submitFormData() {

        try {
          await this.validateForm()

          const transfer2Int = arr => arr.map(v => +v)
          const removeRepeat = (arr) => [...new Set(arr)]
          // const allSet = this.originLineList.map(v => v.lineId).concat(this.resultItems.map(v => v.lineId))
          //   |>transfer2Int|>removeRepeat|> debugLogger('>>>>>>>>> lineId ')

          //  计算出那些需要删除和那些需要新增
          // this.resultItems.reduce((acc, cur) => {
          //   const insertPropName = allSet.includes(+cur.lineId) ? 'insertItems' : 'deleteItems'
          //   return { ...acc, [insertPropName]: [...acc[insertPropName], cur] }
          // }, { insertItems: [], deleteItems: [] }) |> debugLogger('insertItems deleteItems ')

          await DeleteProductLine(this.enumList.map(e => +e.productLineId).filter(v => v))
          const { Result, Code } = await ModifyProductLine(this.resultItems)
          if (Code === ERR_OK) {
            this.$message.success('保存产品线配置成功')
          } else {
            this.$message.warning('保存产品线配置失败')
          }

        } catch (e) {
          console.log(e)
        }
      },
      handleProductDefaultLineChange() {  //  number
        this.updateRes(this.enumList.filter(e => {
          return this.formData.selectIds.includes(e.lineId)
        }).map(e => {
          return {
            ...e, isDefault: e.lineId === this.formData.defaultProductLine
          }
        }))
      },
      handleProductLineChange() { //  array<number>
        this.updateRes(this.enumList.filter(e => {
          return this.formData.selectIds.includes(e.lineId)
        }))
        if (!this.formData.selectIds.includes(this.formData.defaultProductLine)) {
          this.formData.defaultProductLine = ''
        }

      },

      updateRes(...args) {
        this.$emit('update:resultItems', ...args)
      },
      calculate({ lineList, Items } = {}) {
        const def = lineList.find(v => v.isDefault)?.['lineId'] ?? null
          |> debugLogger('def lineId')

        const selId2ObjMap = lineList.reduce((acc, cur) =>
            Reflect.has(acc, cur.lineId) ? acc : { ...acc, [cur.lineId]: cur },
          Object.create(null))

        //  可以改为map
        const id2nameMap = Items.reduce((acc, { LineId, Name }) =>
            Reflect.has(acc, LineId) ? acc : { ...acc, [LineId]: Name },
          Object.create(null))

        const selLineList = lineList.map((v) => ({
          ...v, name: id2nameMap[v.lineId]
        }))

        const selLineIds = selLineList.map(v => v.lineId + '')

        const allItems = Object.keys(id2nameMap).reduce((acc, key) => {
          // return !lineIds.includes(+key) ?
          return Reflect.has(selId2ObjMap, key) ?
            [...acc, {
              isDefault: selId2ObjMap[key].isDefault,
              lineId: key,
              productId: this.productId,
              productLineId: selId2ObjMap[key].productLineId,
              name: id2nameMap[key]
            }] :
            [...acc, {
              isDefault: false,
              lineId: key,
              productId: this.productId,
              // productLineId: 0,
              name: id2nameMap[key]
            }]
          // : acc
        }, [])

        //  算出全部的和当前选中的和默认选中的
        this.enumList = allItems
        this.formData.selectIds = selLineIds
        this.formData.defaultProductLine = def + ''
        this.key++
      },

      async getAll() {
        const { Result: { Items = [] } = {} } = await getAllLine({
          page: 1,
          pagesize: 100,
          inKey: ''
        })
        return Items
      },

      async getRelate() {
        try {
          const { productId } = this
          const { Code, Result } = await QueryProductLine({ productId })
          if (Code === ERR_OK) {
            return Result
          }
        } catch (e) {
          console.log(e)
        }
      }
    }

  }
</script>

<style lang="scss" scoped>

</style>
